package com.offcn.search.web.controller;

import com.offcn.search.feign.SearchFeign;
import com.offcn.search.pojo.Item;
import com.offcn.utils.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Map;

@Controller
@RequestMapping("/search")
public class SearchController {

    @Autowired
    private SearchFeign searchFeign;

    @GetMapping("/list")
    public String search(@RequestParam(required = false) Map searchMap , Model model){
        Map resultMap = searchFeign.search(searchMap);
        model.addAttribute("result",resultMap);
        model.addAttribute("searchMap",searchMap);
        //记录原有的URL
        String url = this.setUrl(searchMap);
        model.addAttribute("url",url);
        Page<Item> page = new Page<Item>(
                Long.valueOf(resultMap.get("total").toString()),
                Integer.valueOf(resultMap.get("pageNum").toString()),
                Integer.valueOf(resultMap.get("pageSize").toString())
        );
        model.addAttribute("page",page);
        return "search";
    }

    private String setUrl(Map<String ,String > searchMap) {
        String url = "/search/list";
        if (searchMap != null && searchMap.size()>0){
            url += "?";
            for (Map.Entry<String, String> entry : searchMap.entrySet()) {
                String key = entry.getKey();
                String value = entry.getValue();
                if (key.equals("pageNum") || key.equals("sortRule") || key.equals("sortField")){
                    continue;
                }
                // /search/list?keywords=手机&网络=移动5g&价格=500-100
                url += key + "=" + value + "&";
            }
            if (url.lastIndexOf("&") != -1){
                url = url.substring(0,url.lastIndexOf("&"));
            }
        }
        return url;
    }
}
